import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { Button, Backdrop, Container, Typography, Paper, Snackbar, Dialog, DialogTitle, DialogContent, DialogContentText, TextField, DialogActions } from '@material-ui/core';
import MuiAlert from '@material-ui/lab/Alert';
import AddIcon from '@material-ui/icons/Add';
import NavigateNextIcon from '@material-ui/icons/NavigateNext';
import PersonAddIcon from '@material-ui/icons/PersonAdd';
import GamesIcon from '@material-ui/icons/Games';
import CircularProgress from '@material-ui/core/CircularProgress';

function Alert(props) {
    return <MuiAlert elevation={6} variant="filled" {...props} />;
}

@inject("baseStore")
@observer
class Start extends Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            errorOpen: false,
            joinOpen: false,
            roomId:"",
            errorMsg:""
        }
    }

    componentDidMount = () => {
        if (!this.props.baseStore.status) {
            this.props.history.push({
                pathname: "/",
                state: this.props.location.pathname
            });
        }
    }

    render() {
        const vertical = "top";
        const horizontal = "center";
        return (
            <div style={{ margin: 0, padding: 0, border: 0 }}>
                <Container fixed maxWidth="sm">
                    <Paper style={{ padding: "20px", marginTop: "30px", marginBottom: "10px", height: "calc(100vh - 200px)" }}>
                        <Typography style={{ marginTop: "10vh", marginBottom: "50px" }}
                            variant="h3" component="h3" gutterBottom>
                            are u ooc ?
                        </Typography>
                        <Button
                            onClick={this.create}
                            style={{ float: "left", margin: "10px", width: "calc(100% - 20px)" }}
                            variant="contained"
                            color="primary"
                            size="large"
                            startIcon={<AddIcon style={{ fontSize: 16 }} />}
                        >
                            创建房间
                        </Button>
                        <Button
                            onClick={()=>{this.setState({joinOpen:true})}}
                            style={{ float: "left", margin: "10px", width: "calc(100% - 20px)" }}
                            variant="contained"
                            color="primary"
                            size="large"
                            startIcon={<GamesIcon style={{ fontSize: 16 }} />}
                        >
                            加入房间
                        </Button>
                        <Dialog open={this.state.joinOpen} onClose={()=>{this.setState({joinOpen:false})}}  aria-labelledby="form-dialog-title">
                            <DialogTitle>输入房间号</DialogTitle>
                            <DialogContent>
                                <DialogContentText>
                                    如果没有房间号，可以去创建新的房间
                                </DialogContentText>
                                <TextField
                                    autoFocus
                                    margin="dense"
                                    label="输入房间号"
                                    fullWidth
                                    value={this.state.roomId}
                                    onChange={(e)=>{this.setState({roomId:e.target.value})}}
                                />
                            </DialogContent>
                            <DialogActions>
                                <Button onClick={()=>{this.setState({joinOpen:false})}} color="primary">
                                    取消
                                </Button>
                                <Button onClick={this.join} color="primary">
                                    确定
                                </Button>
                            </DialogActions>
                        </Dialog>
                        <Button
                            onClick={this.connect}
                            style={{ float: "left", margin: "10px", width: "calc(100% - 20px)" }}
                            variant="contained"
                            color="primary"
                            size="large"
                            startIcon={<PersonAddIcon style={{ fontSize: 16 }} />}
                        >
                            添加好友
                        </Button>
                        <Button
                            onClick={this.connect}
                            style={{ float: "left", margin: "10px", width: "calc(100% - 20px)" }}
                            variant="contained"
                            color="primary"
                            size="large"
                            startIcon={<NavigateNextIcon style={{ fontSize: 16 }} />}
                        >
                            查看规则
                        </Button>

                    </Paper>
                    <Backdrop style={{ zIndex: 999, color: "#fff" }} open={this.state.open} >
                        <CircularProgress color="inherit" />
                    </Backdrop>
                    <Snackbar open={this.state.errorOpen} autoHideDuration={6000} anchorOrigin={{ vertical, horizontal }} >
                        <Alert severity="error">{this.state.errorMsg}</Alert>
                    </Snackbar>

                </Container>

            </div>
        );
    }

    join = () => {
        let body = JSON.stringify({
            "type": "join",
            "roomId": this.state.roomId
        })
        this.props.baseStore.sendMessage(body);
        this.setState({ open: true,joinOpen:false });
        let count = 0;
        const intervalId = setInterval(() => {
            // 每隔一秒钟增加计数器
            if (this.props.baseStore.step === 1) {
                this.props.baseStore.room.roomId = this.state.roomId;
                this.setState({ open: false });
                clearInterval(intervalId);
                this.props.history.push({
                    pathname: "/game",
                    state: this.props.location.pathname
                });
            }
            count++;
            if (count === 100 || this.props.baseStore.errorMsg != "") {
                // 当计数器达到100时，退出  
                clearInterval(intervalId);
                this.setState({ open: false, errorOpen: true, errorMsg:this.props.baseStore.errorMsg });
                setTimeout(() => {
                    this.props.baseStore.errorMsg = "";
                }, 10);
                setTimeout(() => {
                    this.setState({ errorOpen: false });
                }, 2000);
            }
        }, 100);
    }

    create = () => {
        let body = JSON.stringify({ "type": "create" })
        this.props.baseStore.sendMessage(body);
        let count = 0;
        this.setState({ open: true });
        const intervalId = setInterval(() => {
            // 每隔一秒钟增加计数器
            if (this.props.baseStore.room.roomId != undefined && this.props.baseStore.room.roomId !== "") {
                this.setState({ open: false });
                clearInterval(intervalId);
                this.props.history.push({
                    pathname: "/game",
                    state: this.props.location.pathname
                });
            }
            count++;
            if (count === 100 || this.props.baseStore.errorMsg != "") {
                // 当计数器达到100时，退出  
                clearInterval(intervalId);
                this.setState({ open: false, errorOpen: true, errorMsg:this.props.baseStore.errorMsg });
                setTimeout(() => {
                    this.props.baseStore.errorMsg = "";
                }, 10);
                setTimeout(() => {
                    this.setState({ errorOpen: false });
                }, 2000);
            }
        }, 100);
    }
}

export default Start;